/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package DAO;

import java.text.*;
import java.util.*;
import java.sql.*;

import connection.ConnectionManager;
import java.util.logging.Level;
import java.util.logging.Logger;
import model.RegisterBean;
import model.UserBean;

/**
 *
 * @author lg
 */
public class UserDAO {

    Connection currentCon;
    ResultSet rs = null;
    
    public UserDAO(){
        currentCon = ConnectionManager.getConnection();
    }

    /*Method Name : logIn
     *
     *Parameter(s): UserBean >> the bean that the servlet sent which contains only the username 
     *				and password of the current UserBean instance.
     *
     *Description: connects to DB, checks if the user exists , sets valid to true or false accordingly.
     *
     *return type: UserBean >> returns the bean instance to the caller servlet after the updates done to it.
     * 
     **/
    public UserBean login(UserBean bean) {

        // Preparing some objects for connection 
        Statement stmt = null;

        //  Get the username and password from the bean 
        // (Initially entered by the user and saved to the bean by the Servlet)
        String username = bean.getUsername();
        String password = bean.getPassword();



        // Build the query  SELECT * FROM user WHERE username='...' AND password= '...' 
        String searchQuery =
                "select * from user u join userroleuserrelation ur on u.UserID = ur.userID where u.Username='"
                + username
                + "' AND u.Password='"
                + password
                + "'";



        // "System.out.println" prints in the console; Normally used to trace the process
        System.out.println("Your user name is " + username);
        System.out.println("Your password is " + password);
        System.out.println("Query: " + searchQuery);


        try {

            //connect to DB 
            stmt = currentCon.createStatement();


            rs = stmt.executeQuery(searchQuery); 	// Save the results of the query to the ResultSet 'rs'
            boolean more = rs.next();            	// If 'rs' is empty, then more = false; else, more = true



            // If the ResultSet is empty >>> user does not exist >>> set the isValid variable to false
            if (!more) {

                System.out.println("Sorry, you are not a registered user! Please sign up first");
                bean.setValid(false);
            } // If the ResultSet is not empty >>> user exists >>> set the isValid variable to true 
            // And save the user's First and Last names to the bean (To be displayed later by userLogged.jsp)
            else if (more) {
                int RoleID = rs.getInt("RoleID");
                String firstName = rs.getString("FirstName");
                String lastName = rs.getString("LastName");
                int userID = rs.getInt("UserID");
                System.out.println("Welcome " + firstName);
                bean.setFirstName(firstName);
                bean.setLastName(lastName);
                bean.setUserId(userID);
                bean.setValid(true);
                bean.setRoleId(RoleID);
            }


        } catch (Exception ex) {
            System.out.println("Log In failed: An Exception has occurred! " + ex);
        } //Some exception handling
        finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (Exception e) {
                }
                rs = null;
            }

            if (stmt != null) {
                try {
                    stmt.close();
                } catch (Exception e) {
                }
                stmt = null;
            }

            if (currentCon != null) {

                try {
                    currentCon.close();
                } catch (Exception e) {
                }
                currentCon = null;

            }
        }
        return bean;

    }

    public void SignUp(RegisterBean registerBean) {
        try {
            String query = "INSERT INTO user (Username,Password,UstreamUserName,FirstName,LastName) VALUES ('"
                    + registerBean.getEmail() + "','"
                    + registerBean.getPassword() + "','"
                    + registerBean.getUstreamusername() + "','"
                    + registerBean.getFirstname() + "','"
                    + registerBean.getLastname() + "')";
            Statement statement = currentCon.createStatement();
            statement.execute(query);
            query = "SELECT * FROM user ORDER BY UserID DESC LIMIT 1";
            ResultSet rs = statement.executeQuery(query);
            rs.next();
            int userId = rs.getInt("UserID");
            if(registerBean.isType()){ // willingwalker
                query = "INSERT INTO userroleuserrelation (UserID,RoleID) VALUES('"
                        +userId + "','"
                        +1 + "')";
            }
            else{
                query = "INSERT INTO userroleuserrelation (UserID,RoleID) VALUES('"
                        +userId + "','"
                        +2 + "')";
            }
            statement.execute(query);
        } catch (SQLException ex) {
            Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
